package com.example.financialsystem.adapter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;

import com.example.financialsystem.R;
import com.example.financialsystem.fragment.BookDetailFragment;

import java.util.Hashtable;
import java.util.List;

import models.Book;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import others.ServerResponse;

import static others.Const.CURRENT_BOOK;
import static others.Const.IP;
import static others.Const.PORT;
import static others.Const.currentBook;
import static others.Const.currentIdAndNameHashTable;
import static others.Tools.ToastShow;
import static utils.GsonUtil.String2HashtableServerResponse;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {

    private List<Book> mBookList;
    private DrawerLayout drawerLayout;
    private TextView buttonBooks;
    FrameLayout frameLayout;
    private  FragmentManager fragmentManager;
    private int selectedPosition = 0;
    private String responseData;
    public static final int GETNAMEIDHASHTABLE = 1;

    static class ViewHolder extends RecyclerView.ViewHolder{
        View bookView;
        ImageView bookImage;
        TextView bookName;

        public ViewHolder(View view){
            super(view);
            bookView = view;
            bookImage = (ImageView)view.findViewById(R.id.recycler_book_image);
            bookName = (TextView)view.findViewById(R.id.recycler_book_name);
        }
    }

    public BookAdapter(List<Book> bookList,
                       DrawerLayout drawerLayout,
                       TextView buttonBooks,
                       FrameLayout frameLayout,
                       FragmentManager fragmentManager){
        mBookList = bookList;
        this.drawerLayout = drawerLayout;
        this.buttonBooks = buttonBooks;
        this.frameLayout = frameLayout;
        this.fragmentManager = fragmentManager;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_book, parent, false);
        final ViewHolder holder = new ViewHolder(view);

        //点击事件
        holder.bookView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                if (selectedPosition != position) {
                    selectedPosition = position;
                    currentBook = mBookList.get(position);
                    buttonBooks.setText(currentBook.getBookname()+">");
                    if (currentBook.getType() != 0){
                        getBookInformation(currentBook.getId());
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(CURRENT_BOOK,currentBook);
                    BookDetailFragment fragment = new BookDetailFragment();
                    fragment.setArguments(bundle);
                    ReplaceFragment(fragment);
                    drawerLayout.closeDrawer(GravityCompat.START);
                }else {
                    drawerLayout.closeDrawer(GravityCompat.START);
                }
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Book book = mBookList.get(position);
        holder.bookImage.setImageResource(R.drawable.recycler_book_icon);
        holder.bookName.setText(book.getBookname());
    }

    @Override
    public int getItemCount() {
        return mBookList.size();
    }

    public void ReplaceFragment(Fragment fragment){
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.homeFragment,fragment);
        transaction.commit();
    }

    public void getBookInformation(String bookId){
        String url = "http://" + IP + ":" + PORT + "/portal/user/BookInfo.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("bookId",bookId)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    responseData = response.body().string();
                    Message message = new Message();
                    message.what = GETNAMEIDHASHTABLE;
                    handler.sendMessage(message);
                } catch (Exception e){
                    e.printStackTrace();
                    ToastShow("我们可能遭遇了一些麻烦1(BookAdapter)");
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case GETNAMEIDHASHTABLE:
                    ServerResponse<Hashtable<String,String>> serverResponse
                            = String2HashtableServerResponse(responseData);
                    if (serverResponse.getStatus() == 0){
                        currentIdAndNameHashTable = serverResponse.getData();
                        Log.d("test", "更新完成映射hashTable");;
                    }else {
                        ToastShow("我们可能遭遇了一些麻烦2(BookAdapter)");
                    }
                    break;
                default:
                    break;
            }
        }
    };
}
